//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.restaurant.application.bookingset;

import com.google.common.base.Strings;
import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.DateTypes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.definitions.ButtonField;
import com.nebutown.commonunits.dataface.definitions.PageForm;
import com.nebutown.commonunits.dataface.definitions.TimeInterval;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.commonunits.utils.SnowFlake;
import com.nebutown.description.data.SortSpec;
import com.nebutown.generation.basicdata.StringMap;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.bookingset.support.AbstractBookingSet;
import com.restaurant.application.bookingset.support.BookingPageData;
import com.restaurant.application.bookingset.support.BookingSetData;
import com.restaurant.application.bookingset.support.TimesData;
import com.restaurant.application.indexes.bookingsetlist.AssistBookingSetList;
import com.restaurant.application.indexes.bookingsetlist.mysql.BookingSetListBean;
import com.restaurant.application.indexes.bookingsetlist.mysql.BookingSetListCriteria;
import com.restaurant.application.indexes.bookingsetlist.mysql.BookingSetListImpl;
import com.restaurant.application.shop.Shop;
import com.restaurant.application.shop.support.ShopVo;
import com.restaurant.application.shoplist.ShopList;
import com.restaurant.application.util.CommonUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class BookingSetImpl extends AbstractBookingSet {
    public BookingSetImpl() {
    }

    public View getFullView() {
        return this.findView(this.reverseData(this.getData().duplicate()));
    }

    private BookingPageData reverseData(BookingSetData data) {
        BookingPageData pageData = new BookingPageData();
        if (data.getCreateTime() == null) {
            return pageData;
        } else {
            pageData.withShopName(data.getShopName()).withDateInterval((new TimeInterval()).withFrom(CommonUtils.dateTimeToLong(data.getStartDate()) + 28800000L).withTo(CommonUtils.dateTimeToLong(data.getEndDate()) + 28800000L));
            int timeSize = data.getTimes().size();

            int serviceSize;
            for(serviceSize = 0; serviceSize < timeSize; ++serviceSize) {
                TimesData times0;
                if (serviceSize == 0) {
                    times0 = (TimesData)data.getTimes().get(0);
                    pageData.withDefaultTime((new TimeInterval()).withFrom(CommonUtils.reverseTime(times0.getStartTime())).withTo(CommonUtils.reverseTime(times0.getEndTime())));
                } else {
                    times0 = (TimesData)data.getTimes().get(serviceSize);
                    pageData.setValueOf("times" + (serviceSize - 1), (new TimeInterval()).withFrom(CommonUtils.reverseTime(times0.getStartTime())).withTo(CommonUtils.reverseTime(times0.getEndTime())));
                }
            }

            serviceSize = data.getService().size();

            for(int i = 0; i < serviceSize; ++i) {
                String s0;
                if (i == 0) {
                    s0 = (String)data.getService().get(0);
                    pageData.withDefaultService(s0);
                } else {
                    s0 = (String)data.getService().get(i);
                    pageData.setValueOf("service" + (i - 1), s0);
                }
            }

            return pageData;
        }
    }

    public View findView(BookingPageData pageData) {
        PageForm pageForm = this.newFormShell(pageData).getForm();
        return ((UIDataFace)this.getSingleton(UIDataFace.class)).newUniForm(this.unitPosition(), pageForm);
    }

    public View getViewLead(ViewSpec spec) {
        return null;
    }

    public ViewUpdate addTime(BookingPageData pageData, int[] seq) {
        IntStream.range(0, 11).filter((e) -> {
            return Objects.isNull(pageData.getValueOf("times" + e));
        }).findFirst().ifPresent((x) -> {
            pageData.setValueOf("times" + x, new TimeInterval());
        });
        return this.returnView(new View[]{this.findView(pageData)});
    }

    public ViewUpdate removeTime(BookingPageData pageData, int[] seq) {
        pageData.setValueOf("times" + seq[0], (Object)null);
        return this.returnView(new View[]{this.findView(pageData)});
    }

    public ViewUpdate addService(BookingPageData pageData, int[] seq) {
        IntStream.range(0, 6).filter((e) -> {
            return Objects.isNull(pageData.getValueOf("service" + e));
        }).findFirst().ifPresent((x) -> {
            pageData.setValueOf("service" + x, "");
        });
        return this.returnView(new View[]{this.findView(pageData)});
    }

    public ViewUpdate removeService(BookingPageData pageData, int[] seq) {
        pageData.setValueOf("service" + seq[0], (Object)null);
        return this.returnView(new View[]{this.findView(pageData)});
    }

    public ViewUpdate cancel(int[] seq) {
        return this.returnPopFromContainer(this.getId(), false);
    }

    public ViewUpdate save(BookingPageData pageData, int[] seq) {
        if (Strings.isNullOrEmpty(pageData.getShopName())) {
            return this.hasError("请选择门店");
        } else if (pageData.getDateInterval() != null && pageData.getDateInterval().getFrom() != null && pageData.getDateInterval().getTo() != null) {
            long thirtyDay = 2592000000L;
            long min = pageData.getDateInterval().getTo() - pageData.getDateInterval().getFrom();
            if (min <= thirtyDay && min >= 0L) {
                if (pageData.getDefaultTime().getFrom() != null && pageData.getDefaultTime().getTo() != null) {
                    if (pageData.getDefaultTime().getTo() - pageData.getDefaultTime().getFrom() < 0L) {
                        return this.hasError("第1个时间段填写有误！");
                    } else if (Strings.isNullOrEmpty(pageData.getDefaultService())) {
                        return this.hasError("请至少填写一个预约服务");
                    } else {
                        BookingSetData save = this.castData(pageData);
                        if (!Strings.isNullOrEmpty(save.getShopId())) {
                            return this.hasError(save.getShopId());
                        } else {
                            String times = ((AssistBookingSetList)this.getSingleton(AssistBookingSetList.class)).checkIsRepeat(this.getId(), save);
                            if (!Strings.isNullOrEmpty(times)) {
                                return this.hasError(times);
                            } else {
                                if (this.getData().getId() != null) {
                                    save.withId(this.getData().getId()).withCreateTime(this.getData().getCreateTime());
                                } else {
                                    save.withId(SnowFlake.findUniqueId()).withCreateTime(DateTimeUtils.getCurrentMillisecond());
                                }

                                UID uid = ((ShopList)this.getSingleton(ShopList.class)).findShopByName(save.getShopName());
                                String id = ((Shop)this.getUnit(Shop.class, uid)).findData().getId();
                                save.withShopUid(uid).withShopId(id);
                                save.withModifyTime(DateTimeUtils.getCurrentMillisecond());
                                if (this.getData().getCreateTime() == null) {
                                    this.insertBean(save, new BookingSetListBean());
                                } else {
                                    List<BookingSetListBean> beans = ((BookingSetListImpl)this.getIndex(BookingSetListImpl.class)).search((new BookingSetListCriteria()).withBookingSetEquals(this.getId()), (SortSpec)null, 2);
                                    if (beans.size() > 0) {
                                        this.insertBean(save, (BookingSetListBean)beans.get(0));
                                    } else {
                                        this.getLogger().error("not find this booking");
                                    }
                                }

                                this.setData(save);
                                return this.returnPopFromContainer(this.getId(), false);
                            }
                        }
                    }
                } else {
                    return this.hasError("请至少填写一个时间段");
                }
            } else {
                return this.hasError("日期填写错误");
            }
        } else {
            return this.hasError("请填写预约日期");
        }
    }

    private ViewUpdate hasError(String message) {
        return this.returnViewCall(this.buildViewCall(this.unitPosition(), "showErrorMessage", (List)null, (new StringMap()).putData("errorMessage", message)));
    }

    private BookingSetData castData(BookingPageData pageData) {
        BookingSetData data = new BookingSetData();
        data.withShopName(pageData.getShopName());
        String startDate = CommonUtils.longToTimeString(pageData.getDateInterval().getFrom());
        String endData = CommonUtils.longToTimeString(pageData.getDateInterval().getTo());
        data.withStartDate(startDate).withEndDate(endData);
        List<TimesData> times = new ArrayList();
        List<String> services = new ArrayList();
        String startTime = CommonUtils.castTime(pageData.getDefaultTime().getFrom());
        String endTime = CommonUtils.castTime(pageData.getDefaultTime().getTo());
        times.add((new TimesData()).withStartTime(startTime).withEndTime(endTime));
        services.add(pageData.getDefaultService());

        for(int i = 0; i < 11; ++i) {
            if (pageData.getValueOf("times" + i) != null) {
                TimeInterval interval = (TimeInterval)((TimeInterval)pageData.getValueOf("times" + i));
                if (interval.getFrom() != null && interval.getTo() != null) {
                    if (interval.getTo() - interval.getFrom() < 0L) {
                        data.withShopId("第" + (i + 2) + "个时间段填写有误！");
                        break;
                    }

                    String iTime = CommonUtils.castTime(interval.getFrom());
                    String eTime = CommonUtils.castTime(interval.getTo());
                    times.add((new TimesData()).withStartTime(iTime).withEndTime(eTime));
                }
            }

            if (i < 6 && pageData.getValueOf("service" + i) != null) {
                String s = (String)((String)pageData.getValueOf("service" + i));
                if (!Strings.isNullOrEmpty(s)) {
                    services.add(s);
                }
            }
        }

        data.withTimes(times).withService(services);
        return data;
    }

    private void insertBean(BookingSetData save, BookingSetListBean bean) {
        String times = save.getStartDate() + "-" + save.getEndDate();
        String s = (String)save.getTimes().stream().map((e) -> {
            return e.getStartTime().substring(0, e.getStartTime().length() - 3) + "-" + e.getEndTime().substring(0, e.getStartTime().length() - 3);
        }).collect(Collectors.joining(";"));
        String service = String.join(",", save.getService());
        bean.withBookingSet(this.getId()).withId(save.getId()).withDates(times).withTimes(s).withService(service).withCreateTime(save.getCreateTime()).withModifyTime(save.getModifyTime()).withShop(save.getShopUid()).withShopId(save.getShopId()).withShopName(save.getShopName());
        if (bean.getRecordId() == null) {
            ((BookingSetListImpl)this.getIndex(BookingSetListImpl.class)).insert(bean);
        } else {
            ((BookingSetListImpl)this.getIndex(BookingSetListImpl.class)).updateByRecordId(bean);
        }

    }

    public BookingSetData findData() {
        return this.getData().duplicate();
    }

    private FormShell newFormShell(BookingPageData pageData) {
        FormShell formShell = new FormShell("预约设置", 3, 8);
        formShell.source(pageData, DataModes.EDIT);
        List<ShopVo> allShopData = ((ShopList)this.getSingleton(ShopList.class)).findAllShopData();
        List<String> shopList = (List)allShopData.stream().map(ShopVo::getName).collect(Collectors.toList());
        formShell.at(0, 0, "使用门店").selectEntry("shopName", pageData.getShopName(), shopList).placeHolder("门店").notNull().setEditable(true);
        formShell.at(1, 0, "可预约日期").intervalField("dateInterval", pageData.getDateInterval(), DateTypes.DATE).notNull().setEditable(true);
        formShell.at(2, 0, "可预约时间段").intervalField("defaultTime", pageData.getDefaultTime(), DateTypes.TIME).notNull().setEditable(true);
        formShell.at(2, 1, "").buttonBoxField(new ButtonField[]{new ButtonField(this.getPath(CMD_ADDTIME, new int[0]), "+", true, (String)null, false)});
        AtomicInteger i = new AtomicInteger(3);
        IntStream.range(0, 11).forEach((e) -> {
            int row = i.getAndIncrement();
            if (pageData.getValueOf("times" + e) != null) {
                formShell.at(row, 0, "&nbsp;").intervalField("times" + e, (TimeInterval)pageData.getValueOf("times" + e), DateTypes.TIME).notNull().setEditable(true);
                formShell.at(row, 1, "").buttonBoxField(new ButtonField[]{new ButtonField(this.getPath(CMD_REMOVETIME, new int[]{e}), "-", true, (String)null, false)});
            }

        });
        AtomicInteger m = new AtomicInteger(i.getAndIncrement());
        int row2 = m.getAndIncrement();
        formShell.at(row2, 0, "可预约服务").stringField("defaultService", pageData.getDefaultService()).notNull().setEditable(true);
        formShell.at(row2, 1, "").buttonBoxField(new ButtonField[]{new ButtonField(this.getPath(CMD_ADDSERVICE, new int[0]), "添加", true, (String)null, false)});
        IntStream.range(0, 6).forEach((e) -> {
            int row = m.getAndIncrement();
            if (pageData.getValueOf("service" + e) != null) {
                formShell.at(row, 0, "&nbsp;").stringField("service" + e, (String)pageData.getValueOf("service" + e)).notNull().setEditable(true);
                formShell.at(row, 1, "").buttonBoxField(new ButtonField[]{new ButtonField(this.getPath(CMD_REMOVESERVICE, new int[]{e}), "移除", true, (String)null, false)});
            }

        });
        int row3 = m.getAndIncrement();
        if (!Strings.isNullOrEmpty(this.getPath(CMD_SAVE, new int[0]))) {
            formShell.at(row3, 0, "").buttonField(this.getPath(CMD_SAVE, new int[0]), "保存", "创建", true);
        }

        formShell.at(row3, 1, "").buttonField(this.getPath(CMD_CANCEL, new int[0]), "取消", "取消", true);
        return formShell;
    }
}
